//
//  HBTableViewFooterView.m
//  FMSManager
//
//  Created by hongbao.cui on 15-1-9.
//  Copyright (c) 2015年 hongbao.cui. All rights reserved.
//

#import "HBTableViewFooterView.h"
#import "HBTableViewHeaderView.h"
#import "ApplicationUtils.h"
@implementation HBTableViewFooterView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        NSInteger x= 0.0;
        NSInteger y = 20.0;
        
        UIImageView *lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, y, 280, 1)];
        [lineImageView setImage:[UIImage imageNamed:@"st_line.png"]];
        [lineImageView setHidden:NO];
        [self addSubview:lineImageView];
        if (!_anylisewebView) {
            _anylisewebView = [[UIWebView alloc] initWithFrame:CGRectMake(x,y,FMSCREENWIDTH-20,40)];
            [_anylisewebView setBackgroundColor:[UIColor greenColor]];
            [_anylisewebView setUserInteractionEnabled:NO];
            [_anylisewebView setOpaque:NO];
            [_anylisewebView setDelegate:self];
            [self addSubview:_anylisewebView];
        }
        
        
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fakeTapGestureHandler:)];
        
        [tapGestureRecognizer setDelegate:self];
        [self addGestureRecognizer:tapGestureRecognizer];
    }
    return self;
}
-(void)fakeTapGestureHandler:(UITapGestureRecognizer *)gesture{
    int scrollPositionY = [[_anylisewebView stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] intValue];
    int scrollPositionX = [[_anylisewebView stringByEvaluatingJavaScriptFromString:@"window.pageXOffset"] intValue];
//    int displayWidth = [[_anylisewebView stringByEvaluatingJavaScriptFromString:@"window.outerWidth"] intValue];
    CGFloat scale =1.0; //_anylisewebView.frame.size.width / displayWidth;
    
    CGPoint pt = [gesture locationInView:_anylisewebView];
    pt.x *= scale;
    pt.y *= scale;
    pt.x += scrollPositionX;
    pt.y += scrollPositionY;
    
    NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", pt.x, pt.y];
    NSString * tagName = [_anylisewebView stringByEvaluatingJavaScriptFromString:js];
    FMSCHBLog(@"tagName =%@", tagName);
    if ([tagName isEqualToString:@"img"]||[tagName isEqualToString:@"IMG"]) {
        NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y];
        NSString *urlToSave = [_anylisewebView stringByEvaluatingJavaScriptFromString:imgURL];
       NSString *fileName =  [[urlToSave componentsSeparatedByString:@"/"] lastObject];
        if ([fileName isEqualToString:@"st_Options_mark_001.png"]||[fileName isEqualToString:@"st_Options_mark_001@2x.png"]||[fileName isEqualToString:@"st_Options_mark_002@2x.png"]||[fileName isEqualToString:@"st_Options_mark_002.png"]) {
            return;
        }
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *docDir = [[paths objectAtIndex:0] stringByAppendingString:[NSString stringWithFormat:@"/Paper/image/%@",fileName]];
        NSURL *fileURL = [NSURL fileURLWithPath:docDir];
        UIImage *image = [UIImage imageWithData:[NSData
                                dataWithContentsOfURL:fileURL]];
//        UIImage *image = [UIImage imageWithContentsOfFile:docDir];//Default-568h@2x 2.png
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        CGPoint point = [keyWindow convertPoint:pt fromView:self];
        
        HBUIImageView *imageView = [[HBUIImageView alloc] initWithFrame:CGRectMake(point.x, point.y, 0, 0)];
        [keyWindow addSubview:imageView];
        [UIView animateWithDuration:0.5 animations:^{
             [imageView setFrame:CGRectMake(0, 0, FMSCREENWIDTH, FMSCREENHEIGHT)];
        } completion:^(BOOL finished) {
            if (finished) {
                [imageView setImage:image];
            }
        }];
    }
}
// Delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES; // Return NO to prevent html document from receiving the touch event.
}
-(void)setDataReload:(NSDictionary *)dict{
    NSString *user_answer = [dict objectForKey:@"user_answer"];
    NSString *answer = [dict objectForKey:@"answer"];
    NSString *qtype = [dict objectForKey:@"qtype"];
    NSString *subAnswerStr = answer;
    NSString *analysis_user = [dict objectForKey:@"analysis"];
    if ((![qtype isEqualToString:@"1"]||![qtype isEqualToString:@"2"]||![qtype isEqualToString:@"3"])&&([[dict allKeys] containsObject:@"has_sub_Array"])) {
        NSMutableString *answerStr = [[NSMutableString alloc] initWithCapacity:1.0];
        NSMutableString *user_answer_str = [[NSMutableString alloc] initWithCapacity:1.0];
        NSMutableString *analysis_str = [[NSMutableString alloc] initWithCapacity:1.0];
        NSArray *array = [dict objectForKey:@"has_sub_Array"];
        NSInteger count=1;
        for (NSDictionary *sub_Dict in array) {
            NSString *answer = [sub_Dict objectForKey:@"answer"];
            NSString *answer_user = [sub_Dict objectForKey:@"user_answer"];
            NSString *analysis_user = [dict objectForKey:@"analysis"];
            if ([answer_user isEqualToString:@""]) {
                answer_user = @"您没有选择答案";
            }
            if ([analysis_user isEqualToString:@""]) {
                analysis_user = @"暂无试题分析";
            }
            [answerStr appendFormat:@"<p>(%ld)%@</p>",(long)count,answer];
            [user_answer_str appendFormat:@"(%ld)%@",(long)count,answer_user];
            [analysis_str appendFormat:@"<p>(%ld)%@</p>",(long)count,analysis_user];
            count++;
        }
        subAnswerStr =answerStr;
        user_answer = user_answer_str;
        analysis_user = analysis_str;
    }
    if ([analysis_user isEqualToString:@""]) {
        analysis_user = @"暂无试题分析";
    }
    NSRange range;
    if (answer.length>7) {
        range.location =3;
        range.length =answer.length-7;
    }else{
        range.location =0;
        range.length =answer.length;
    }
    answer = [answer substringWithRange:range];
    
    NSString *imageStr = @"st_Options_mark_002@2x.png";
    if (![user_answer isEqualToString:@""]&&[user_answer isEqualToString:answer]) {
        imageStr = @"st_Options_mark_002@2x.png";
    }else{
        imageStr = @"st_Options_mark_001@2x.png";
        if ([user_answer isEqualToString:@""]||[user_answer isEqualToString:@"(null)"]) {
            user_answer = @"您没有选择答案";
        }
    }
    NSString *anyliseHTMLData = [NSString stringWithFormat:@"<p><a><font color=\"#0000FF\">您的答案:</font>%@     </a><img src=\"%@\" width=\"18\"></p><p><a><font color=\"#0000FF\">知识点:</font>%@</a></p><p><a><font color=\"#0000FF\">正确答案:</font>%@</a></p><a><font color=\"#0000FF\">试题分析:</font> %@</a>",user_answer,imageStr,[dict objectForKey:@"category_name"],subAnswerStr,analysis_user];
    NSURL *url = nil;
    NSFileManager*fileManager =[NSFileManager defaultManager];
    NSError*error;
    NSString *path = [NSString stringWithFormat:@"%@/image",FMPAPERSAVE_PATH];
    if ([ApplicationUtils isFileExitsAtPath:path]) {
        FMSCHBLog(@"目录创建成功");
    }
    NSString*resourcePath =[[NSBundle mainBundle] pathForResource:[imageStr stringByDeletingPathExtension] ofType:@"png"];
    [fileManager copyItemAtPath:resourcePath toPath:[NSString stringWithFormat:@"%@/%@",path,imageStr] error:&error];
//    if ([qtype isEqualToString:@"0"]) {
//        NSString *path = [NSString stringWithFormat:@"%@",FMPAPERSAVE_PATH];
//        url = [NSURL fileURLWithPath:path];
//        anyliseHTMLData = [NSString stringWithFormat:@"<p><a><font color=\"#0000FF\">您的答案:</font>%@     </a></p><p><a><font color=\"#0000FF\">知识点:</font>%@</a></p><p><a><font color=\"#0000FF\">正确答案:</font>%@</a></p><a><font color=\"#0000FF\">试题分析:</font> %@</a>",user_answer,[dict objectForKey:@"category_name"],subAnswerStr,analysis_user];
//    }else{
//        url = [[NSBundle mainBundle] bundleURL];
//    }
    url = [NSURL fileURLWithPath:path];
    [_anylisewebView setBackgroundColor:[UIColor clearColor]];
    [_anylisewebView loadHTMLString:anyliseHTMLData baseURL:url];
    [self addSubview:_anylisewebView];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    _anylisewebView.frame =CGRectMake(0, 20, FMSCREENWIDTH, _anylisewebView.frame.origin.y+_anylisewebView.scrollView.contentSize.height+10);
    self.frame = CGRectMake(0, 20, FMSCREENWIDTH, _anylisewebView.frame.origin.y+_anylisewebView.scrollView.contentSize.height+10);
    
    if (_delegate&&[_delegate respondsToSelector:@selector(HBTableViewFooterView:webViewDidFinishLoad:)]) {
        [_delegate HBTableViewFooterView:self webViewDidFinishLoad:webView];
    }
}
-(void)dealloc{
    _delegate = nil;
    _anylisewebView.delegate = nil;
}
@end
